package benchmark.energy;

import benchmark.energy.tx.ImportTemporalDataTx.MultiEntityEnergyStatus;
import com.google.common.collect.AbstractIterator;

import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class EnergyStatusCsvReader extends AbstractIterator<MultiEntityEnergyStatus> implements Closeable {
    private final BufferedReader reader;
    private final Map<Integer, Integer> idColMap = new HashMap<>();

    public EnergyStatusCsvReader(File file) throws IOException {
        reader = new BufferedReader(new FileReader(file));
        String header = reader.readLine();
        parseHeader(header);
    }

    @Override
    protected MultiEntityEnergyStatus computeNext() {
        try {
            String line = reader.readLine();
            if (line == null) {
                return endOfData();
            } else {
                return parseLine(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("fail to read traffic file.");
        }
    }

    private void parseHeader(String header) {
        String[] arr = header.split(",");
        for(int i=1; i<arr.length; i++){
            idColMap.put(i, Integer.parseInt(arr[i]));
        }
    }

    private MultiEntityEnergyStatus parseLine(String line) {
        HashMap<Integer, Float> r = new HashMap<>();
        String[] arr = line.split(",");
        for(int i=1; i<arr.length; i++){
            Integer id = idColMap.get(i);
            r.put(id, Float.parseFloat(arr[i]));
        }
        MultiEntityEnergyStatus e = new MultiEntityEnergyStatus();
        e.setStatus(r);
        e.setTimePoint(parseTime(arr[0]));
        return e;
    }

    private int parseTime(String s) {
        String[] arr0 = s.split(" ");
        assert arr0.length==2;
        String[] arr1 = arr0[0].split("/");
        assert arr1.length==3;
        String[] arr2 = arr0[1].split(":");
        assert arr2.length==2;
        Calendar c = Calendar.getInstance();
        c.set(Integer.parseInt(arr1[0]), Integer.parseInt(arr1[1])-1, Integer.parseInt(arr1[2]), Integer.parseInt(arr2[0]), Integer.parseInt(arr2[1]));
        return Math.toIntExact(c.getTimeInMillis() / 1000);
    }

    public void close() throws IOException {
        reader.close();
    }

}
